<template>
    <HeadImage :background="backPath" style="height: 25vh">
        <p slot="two" class="head">{{disposition[0]}}</p>
    </HeadImage>
         <div class="box"
              :style="{
                  'color': $store.state.nowTime==='moon' ? '#fff' : '#8f8c8c',
                  'background':   $store.state.nowTime==='moon' ? 'rgba(38,37,37,0.7)' : 'rgba(255, 255, 255, 0.7)'
             }">
             <div class="left">
                  <div class="left_head">
                      <img :src="fileImg" alt="">
                         <a class="file "   @change="getFile" >上传头像
                             <input type="file" name="file" id="myFile"   ref="img" >
                         </a>
                      <a class="bth" v-show="file" @click="submit">保存</a>

                      <span class="logout" @click="logout_">注销账号</span>
                  </div>
                 <div class="left_body">
                   <div class="userInfo">
                       <span class="edit" >个人信息</span>
                       <span class="edit" ref="edit" @click="edits">编辑</span>
                   </div>
                     <div class="info">
                      <div class="label">
                          Name:
                        <input type="text"
                               ref="username"
                                 placeholder="用戶名"
                                 :class="{'disabled':read}"
                                 maxlength="20"
                                 v-model="userInfo.username"
                                 :readonly="read ? false : 'readonly'">
                      </div>
                         <div class="label">
                             Birth:
                             <input type="text"  placeholder="生日"
                                    :class="{'disabled':read}"
                                    v-model="userInfo.born"
                                    @focus="ofBirthdays"
                                    :readonly="read ? false : 'readonly'"
                                    style="position: relative"
                             >
                             <div class="birthday">
                                 <select v-model="born_year">
                                     <option v-for="item in year" >{{item}}</option>
                                 </select>
                                 <select v-model="born_month">
                                     <option v-for="item in month" >{{item}}</option>
                                 </select>
                                 <select v-model="born_day">
                                     <option v-for="item in day" >{{item}}</option>
                                 </select>
                                 <span
                                 style="color: white ;background: #3586f1;padding: 6px 10px;font-size: 13px"
                                 @click="ouBirthdays"
                                 >確定</span>
                             </div>
                         </div>
                         <div class="label">
                             Age:
                             <input type="text"
                                    disabled
                                     placeholder="年龄"
                                    v-model="userInfo.age">
                         </div>

                         <div class="sex label">
                             <div style="width: 100%" class="sex_content">
                                 Sex:
                                 <label class="sex_content">  <input type="radio" value="1" v-model="userInfo.sex"  :class="{'disabled':read}"  :disabled="read ? false : 'disabled'" name="sex">男</label>
                                 <label class="sex_content">  <input type="radio" value="0" v-model="userInfo.sex"  :class="{'disabled':read}"  :disabled="read ? false : 'disabled'" name="sex">女</label>
                             </div>
                          </div>
                        <div  class="label">
                            Phone:
                            <input type="text"
                                   ref="phone"
                                   placeholder="电话"
                                   :class="{'disabled':read}"
                                   :readonly="read ? false : 'readonly'"
                                   v-model="userInfo.phone">
                        </div>
                         <div  class="label">
                             Email:
                             <input type="email"
                                    ref="email"
                                    placeholder="邮箱"
                                    :class="{'disabled':read}"
                                    :readonly="read ? false : 'readonly'"
                                    v-model="userInfo.email">
                         </div>

                         <p style="color: #8f8c8c">Moto:</p>
                         <textarea  class="motto" placeholder="座右铭"
                                    :class="{'disabled':read}"
                                    :readonly="read ? false : 'readonly'"
                                    v-model="userInfo.motto"
                                    maxlength="50 "
                         ></textarea>

                     </div>
                 </div>
             </div>



             <div class="right">
                 <ul class="navigation">
                     <li id="navigation_li" @click="handoffed1()" >
                         最近文章
                     </li>
                     <li id="navigation_li" @click="handoffed2()">
                         消息<img src="/img/common/tishi.png" alt="" title="消息" style="width: 20px">
                         <span class="tishi_l" v-show="messageSum > 0">{{messageSum >99 ? 99 : messageSum }}</span>
                     </li>
                 </ul>
                 <UserRecentArticles v-if="handoff" ></UserRecentArticles>
                 <MessageDisplay v-else @messages="messageSum_"></MessageDisplay>
             </div>
         </div>
    <div class="box_big"></div>
    <AccountCancellation v-show="shutDown" @shutDown="shutDown_"></AccountCancellation>

</template>

<script>
import HeadImage from "@/components/PublicComponents/HeadImage.vue";
import RecentArticles from "@/components/home/RecentArticles.vue";
import UserRecentArticles from "@/components/home/UserRecentArticles.vue";
import MessageDisplay from "@/components/PublicComponents/MessageDisplay.vue";
import api from "@/api";
import SiteInformation from "@/components/PublicComponents/SiteInformation.vue";
import AccountCancellation from "@/components/PublicComponents/AccountCancellation.vue";
import {baseUrl} from "@/config/global/global";

export default {
    name: "PersonalInformation",
    components: {AccountCancellation, SiteInformation, MessageDisplay, UserRecentArticles, RecentArticles, HeadImage},
    data(){
        return{
            backPath:"",
            year:[],
            month:[1,2,3,4,5,6,7,8,9,10,11,12],
            day:[],
            read:false,
            userInfo:{
                avatar:"",
                phone:"",
                born:"",
                sex:"",
                age:"",
                email:"",
                motto:"",
                username:"",
            },
            ModifyCompletely:{
                username:true,
                email:true,
                phone:true,
            },
            born_year:"1999",
            born_month:"12",
            born_day:"1",
            handoff:true,
            fileImg:"",
            file:"",
            disposition:"",
            messageSum:"",
            shutDown:false,
        }
    },
    created() {
        //获取用户信息
        let user = JSON.parse(window.localStorage.getItem("user"));
        if(user!=null){
            this.userInfo = user;
            this.userInfo.age = this.age_(this.userInfo.born)
            this.fileImg = user.avatar
            this.messageSum_();
        }
    },
    mounted() {
        setTimeout(()=>{
            let writing = JSON.parse(window.localStorage.getItem("DataContent"));
            if(writing){
                        this.disposition = writing[13].content.split("|||||");
                        this.backPath = writing[12].content;
            }
        },200)

        //年份
        for(let i=1850;i<2099;i++){
            this.year.push(i);
        }
        //日
        for(let i=1;i<32;i++){
            this.day.push(i);
        }
        let li = document.querySelectorAll("#navigation_li");
        for(let i=0;i<li.length;i++){
             li[i].addEventListener("click",()=>{
                 for(let j=0;j<li.length;j++){
                     li[j].style.color = "#8f8c8c";
             }
                 li[i].style.color = "#4b73f1";

             })
        }
    },
    watch:{
        'userInfo.email'(){
               let email = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/ ;
               this.ModifyCompletely.email = email.test(this.userInfo.email);
            },
        'userInfo.phone'(){
            let phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
            this.ModifyCompletely.phone = phone.test(this.userInfo.phone);
        },
        'userInfo.username'(){
            let name = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
            this.ModifyCompletely.username = name.test(this.userInfo.username);
        },
    },
    methods:{
        shutDown_(){
            this.shutDown = false;
        },
        logout_(){
           this.shutDown = true;
        },
        messageSum_(){
            api.communicationGetSum().then((res)=>{
                if(res.data.code === 200){
                    this.messageSum = res.data.data;
                }
            })
        },
        handoffed1(){
            this.handoff = true;
        },
        handoffed2(){
            this.handoff = false;
        },
        edits(){
            this.read = !this.read;
            let b = document.querySelector(".birthday");
            b.style.display="none"
            if(this.read){
                this.$refs.edit.innerHTML = "提交"
            }
            else {
                if(this.ModifyCompletely.email && this.ModifyCompletely.phone  && this.ModifyCompletely.username){
                    this.$refs.edit.innerHTML = "编辑"
                    alert("信息更新成功")
                    this.updateUserInfo(this.userInfo);
                }else {
                    this.read = !this.read;
                    alert("信息更新失败，请仔细检查")
                }
            }

        },
        updateUserInfo(userInfo){
             api.updateUserInfo(userInfo).then((res)=>{
                 window.localStorage.setItem("user",JSON.stringify(userInfo))
             })
        },
        ouBirthdays(){
            let b = document.querySelector(".birthday");
            this.userInfo.born = this.born_year+"-"+this.born_month+"-"+this.born_day;
            let dat = new Date();
            if( this.born_year>dat.getFullYear()){
                alert("出生年月过大或过小！")
                return;
            }
          let age = dat.getFullYear() - this.born_year;
            if(this.born_month  <  dat.getMonth()+1)
                 this.userInfo.age = age+1;
                else if(this.born_month  ===  dat.getMonth()+1 && this.born_day> dat.getDate())
                   this.userInfo.age = age+1;
                else    this.userInfo.age = age;

            b.style.display="none"

        },
        ofBirthdays(){
            if(!this.read)
                return
            let b = document.querySelector(".birthday");
            b.style.display="block"
        },


        //发送单个图片,例如上传头像
        getFile() {
            let myFile = document.getElementById('myFile')
            console.log()
            if (myFile.files[0].size > 1024 * 1024*4) {
                alert('单张图片大小不能超过 4MB!');
                return "";
            }
            if (myFile.files.length > 1) {
                alert("只能选中一张图片")
                return;
            }
            this.file = myFile.files[0]
            let url = window.URL || window.webkitURL
            this.fileImg = url.createObjectURL(this.file)
        },
        age_(birthday){
            let age='';
            if(birthday) {
                let str = birthday.split('-');
                // 新建日期对象
                let date = new Date()
                age = date.getFullYear() - parseInt(str[0])
                let age_month = date.getMonth() + 1 - parseInt(str[1])
                let age_date = date.getDate() - parseInt(str[2])
                if (age > 0) {
                    if (age_month < 0) {
                        age -= 1
                    }else if(age_month === 0){
                        if(age_date < 0){
                            age -= 1
                        }
                    }
                }
            }
            return age > 0 ? age : 0;
        },
        submit(){
            let _this = this;
            // 添加需要上传的文件
            const form = new FormData();
            form.append('file', this.file);
            form.append('oldImg',this.userInfo.avatar);
            api.uploadUserHeader(form).then((res)=>{
                if(res.data.code === 200){
                   alert("上传成功")
                       this.userInfo.avatar = res.data.data;
                       this.fileImg = res.data.data;
                       window.localStorage.setItem("user", JSON.stringify(_this.userInfo));
                }else {
                    alert("上传失败")
                }
            })
        },

    }
}
</script>

<style scoped>

.logout{
    position: absolute;
    top: 3%;
    right: 3%;
    font-size: 12px;
    transition: all .1s;
}
.logout:hover{
    color: #3586f1;
    cursor: pointer;
    text-decoration: underline;
}
.tishi_l{
    position: absolute;
    top: 3%;
    right: 0.5%;
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 18px;
    min-height: 18px;
    text-align: center;
    border-radius: 50%;
    background: #ee4f4f;
    font-size: 13px;
    color: white;
}
textarea{
    outline: none;
    resize: none;
    color: #8f8c8c;
    background: transparent;
    border-bottom-color: #8f8c8c;
}
input{
    width: 85%;
    padding:10px;
    padding-bottom: 3px;
    margin-bottom: 10px;
    border: 1px solid transparent;
    outline: none;
    color: #8f8c8c;
    background: transparent;
    border-bottom-color: #8f8c8c;
}


textarea::placeholder{
    color: #8f8c8c;
}
input::placeholder{
    color: #8f8c8c;
}

.box_big {
    width: 100%;
    height: 50px;
}
   .box{
       width: 61vw;
       min-width: 470px;
       margin:50px auto 0;
       height: 30vh;
       min-height: 550px;
       display: flex;
       justify-content: space-between;
       align-items: center;
       min-font-size: 14px !important;
   }

   .left{
       height: 100%;
       width: 20vw;
       min-width: 170px;
       transition: all .7s;
       box-shadow: 1px 1px 5px 2px rgba(141, 135, 135, 0.6);
       animation: box .5s ease-in-out 0s 1 forwards;
   }
@keyframes box {
    0%{
        transform: scaleX(0);
    }100%{
         transform: scaleX(1);
     }
}

   .right{
       height: 100%;
       width: 45vw;
       min-width: 300px;
       transition: all .7s;
       box-shadow: 1px 1px 5px 2px rgba(171, 167, 167, 0.6);
   }
   .left_head{
       display: flex;
       flex-direction: column;
       justify-content: center;
       align-items: center;
       padding: 5px;
       height: 30%;
   }
  .left_head img{
      width: 6vw;
      height: 12vh;
      min-width: 80px;
      min-height: 80px;
      border-radius: 50%;
      margin-bottom: 5px;
      object-fit: cover;
  }
   .left_head p{
       display: flex;
       justify-content: space-between;
       align-items: center;
       color: #4b73f1;
       padding: 2px !important;
       transition: all .5s;
       border: 1px solid transparent;
   }
   .left_head p::after{
       display: inline-block;
       top: 0;
       content: "";
        width: 2.5vw;
       height: 2.5vh;background: url("/img/common/bianji.png") no-repeat center;
       background-size: 50%;
   }
   .left_head p:hover{
       cursor: pointer;
       border-bottom: 1px solid #4b73f1;
   }
   .left_body{
      height: 70%;
      padding: 5px;
   }
   .edit{
       text-align: right !important;
       padding: 5px;
       color: #4b73f1;
       z-index: 99;
   }
   .edit:hover{
       cursor: pointer;
       opacity: .9;
   }

   .userInfo{
       display: flex;
       justify-content: space-between;
       align-items: center;
   }
   .info{
       width: 100%;
       height: 100%;
       /*background: #68c070;*/
   }
.birthday{
    position: absolute;
    bottom: -52%;
    z-index: 9;
    display: none;
}
.birthday span:hover{
    cursor: pointer;
    opacity: .9;
}
.motto{
    padding: 5px;
    width: 95%;
    height: 15%;
    min-height: 50px;
    font-size: 15px;
    margin-left: 1vw;
}
.disabled{
    color: #3586f1 !important;

}
.disabled::placeholder{
    color: #6d7175;
    background: transparent;
}
.sex{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.sex input{
    position: relative;
    width: auto;
    margin-left: 20px;
}

.label{
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 40px;
    font-size: 13px;
    color: #8f8c8c;
}
.navigation{
     display: flex;
    justify-content: left;
    align-items: center;
    height: 5vh;
    min-height: 40px;
    border-bottom: 1px solid #8f8c8c;
}
.navigation li{
    display: flex;
    align-items: center;
    padding:2px 10px;
    height: 100%;
    color: #8f8c8c;
    font-size: 15px;
}
.navigation li:first-child{
    color: #4b73f1;
}
.navigation li:hover{
    cursor: pointer;
    opacity: .9;
    color: #4b73f1;
}
.file {
    position: relative;
    display: inline-block;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
    cursor: pointer;
}
.bth{
    display: inline-block;
    padding: 0 10px;
    color: #004974;
}
.bth:hover{
    cursor: pointer;
    text-decoration: underline;
}
.sex_content{
    display: flex;
    align-items: center;
}
input[type='radio']{
    margin-bottom: 0;
}
</style>